package cn.teaseed.view;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.teaseed.comn.CorsParam;
import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.Initializable;
import javafx.scene.image.ImageView;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.ResourceBundle;

@Data
@Slf4j
@Component
public class ImageQrView implements Initializable {

    public ImageView dGLabImage;

    @Value("${server.port}")
    private String port;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //地址拼接
        String url = "https://www.dungeon-lab.com/app-download.php#DGLAB-SOCKET#";

        //识别192.168开头的局域网地址
        String routerAssignedIp = getRouterAssignedIp();
        String wsUrl = "ws://{}:{}/";

        //如果手动设置配置文件就覆盖识别地址
        if (!StrUtil.isEmpty(CorsParam.manualURL)) {
            routerAssignedIp = CorsParam.manualURL;
        }

        String paramUrl = StrUtil.format(wsUrl, routerAssignedIp, port) + CorsParam.clientID;
        //二维码生成
        QrConfig config = new QrConfig(300, 300);
        // 设置边距，即二维码和背景之间的边距
        config.setMargin(3);
        // 生成二维码流
        BufferedImage generate = QrCodeUtil.generate(url + paramUrl, config);
        // 将 BufferedImage 转换为 JavaFX Image
        dGLabImage.setImage(SwingFXUtils.toFXImage(generate, null));
    }

    public static String getRouterAssignedIp() {
        LinkedHashSet<String> strings = NetUtil.localIpv4s();

        if (strings.isEmpty()) {
            log.error("无法找到本地网络接口");
        }

        String assignedIp = null;
        for (String inetAddress : strings) {
            if (inetAddress.startsWith("192.168")) {
                assignedIp = inetAddress;
                break;
            }
        }

        if (assignedIp == null) {
            log.error("无法找到路由器分配给本机的IP地址");
        }

        log.info("本机局域网IP："+ assignedIp);
        return assignedIp;
    }

}
